// src/hooks/usePolling.ts
import { useEffect, useRef, useCallback } from 'react';

interface UsePollingOptions {
  interval?: number;
  enabled?: boolean;
  onError?: (error: Error) => void;
}

/**
 * 轮询 Hook - 用于定期获取数据
 */
export const usePolling = (
  callback: () => Promise<void> | void,
  options: UsePollingOptions = {}
) => {
  const { interval = 5000, enabled = true, onError } = options;
  const savedCallback = useRef(callback);
  const timeoutRef = useRef<NodeJS.Timeout>();

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  const executePoll = useCallback(async () => {
    try {
      await savedCallback.current();
    } catch (error) {
      onError?.(error as Error);
    }
  }, [onError]);

  useEffect(() => {
    if (!enabled) {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      return;
    }

    const poll = async () => {
      await executePoll();
      timeoutRef.current = setTimeout(poll, interval);
    };

    // 立即执行一次
    executePoll();
    timeoutRef.current = setTimeout(poll, interval);

    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [interval, enabled, executePoll]);
};


